package com.yy.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yy.common.annotation.SysLog;
import com.yy.enums.FileBusinessTypeEnum;
import com.yy.model.InformationEntity;
import com.yy.model.SysFileuploadEntity;
import com.yy.service.InformationService;
import com.yy.service.SysFileuploadService;
import com.yy.utils.HtmlRegexpUtil;
import com.yy.utils.PageUtils;
import com.yy.utils.PropertiesUtil;
import com.yy.utils.Query;
import com.yy.utils.exception.RRException;
import com.yy.utils.ResponseEntity;
import com.yy.utils.file.FileUploadUtil;
import com.yy.validator.Assert;
import com.yy.validator.ValidatorUtils;
import com.yy.validator.group.AddGroup;
import com.yy.validator.group.UpdateGroup;


/**
 * 信息
 * 
 * @author yy
 * @email 
 * @date 2017-07-14 16:15:17
 */
@RestController
@RequestMapping("/information")
public class InformationController extends AbstractController{
	@Autowired
	private InformationService informationService;
	@Autowired
	private SysFileuploadService sysFileuploadService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("information:list")
	public ResponseEntity list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<InformationEntity> informationList = informationService.queryList(query);
		for (InformationEntity information : informationList) {
			String content = HtmlRegexpUtil.filterHtml(information.getContent());
			information.setContent(content);
			information.setImage(information.getImageHttpPath(FileBusinessTypeEnum.NewsImg.getCode()) + information.getImage());
		}
		int total = informationService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(informationList, total, query.getLimit(), query.getPage());
		
		return ResponseEntity.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("information:info")
	public ResponseEntity info(@PathVariable("id") Integer id){
		InformationEntity information = informationService.queryObject(id);
		
		return ResponseEntity.ok().put("information", information);
	}
	
	/**
	 * 图片上传-改名-按时间储存-接口
	 * @param file 文件
	 * @param fileName 文件名 
	 * @param dirName 文件储存目录
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/imageUpload")
	public ResponseEntity imageUpload(@RequestParam(value="imageFile",required=false)MultipartFile imageFile,
			@RequestParam(name="fileName",required=false)String fileName/*,@RequestParam(name="dirName",required=false)String dirName*/){
		if (imageFile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String dirName = FileBusinessTypeEnum.NewsImg.getCode();
		//图片名
		String imageName = FileUploadUtil.reportImgName(imageFile, dirName, fileName);
		if(imageName==null){
			return  ResponseEntity.error("上传失败");
		}
		//图片远程路径
		String imgstr = String.format("%s%s%s",PropertiesUtil.getImgHttpAddress(),dirName,"/");
		String imagestr=String.format("%s%s%s",new SimpleDateFormat("yyyy/MM").format(System.currentTimeMillis()),"/",imageName);
		String imgPath = imgstr+imagestr;
		Map<String, Object> map = new HashMap<>();
		map.put("imgPath", imgPath);
		map.put("imagestr", imagestr);
		
		SysFileuploadEntity sysFileupload =new SysFileuploadEntity();
		sysFileupload.setUrl(imgPath);
		sysFileupload.setCreateDate(new Date());
		sysFileuploadService.save(sysFileupload);
		return  ResponseEntity.ok(map);
	}
	
	/**
	 * 保存
	 */
	@SysLog("保存信息")
	@RequestMapping("/save")
	@RequiresPermissions("information:save")
	public ResponseEntity save(@RequestBody InformationEntity information){
		ValidatorUtils.validateEntity(information, AddGroup.class);
		Assert.isBlank(information.getImage(), "图片名称为空");
		
		if (!StringUtils.isBlank(information.getContent())) {
			try {
				information.setContent(URLDecoder.decode(information.getContent(),"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		//Assert.isNumber(information.getRank(), "排序小于零");
		
		information.setCreateBy(getUser().getUsername());
		informationService.save(information);
		
		return ResponseEntity.ok();
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改信息")
	@RequestMapping("/update")
	@RequiresPermissions("information:update")
	public ResponseEntity update(@RequestBody InformationEntity information){
		ValidatorUtils.validateEntity(information, UpdateGroup.class);
		//Assert.isNumber(information.getRank(), "排序小于零");
		if (!StringUtils.isBlank(information.getContent())) {
			try {
				information.setContent(URLDecoder.decode(information.getContent(),"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		//information.setCreateBy(getUser().getUsername());
		informationService.update(information);
		
		return ResponseEntity.ok();
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除信息")
	@RequestMapping("/delete")
	@RequiresPermissions("information:delete")
	public ResponseEntity delete(@RequestBody Integer[] ids){
		for (Integer integer : ids) {
			InformationEntity information =informationService.queryObject(integer);
			FileUploadUtil.deleteFile(FileBusinessTypeEnum.NewsImg.getCode(), information.getImage());
		}
		informationService.deleteBatch(ids);
		
		return ResponseEntity.ok();
	}
	
}
